package com.cauli.manage.user.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.cauli.manage.user.model.vo.OnlineVO;
import com.cauli.manage.user.model.dto.OnlineQueryDTO;
import com.cauli.manage.user.model.entity.User;
import com.cauli.utils.util.ResultResponse;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.qiwenshare.common.anno.MyLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Cauli
 * @date 2023/4/2 17:58
 * @description 在线用户 前端控制器
 */
@Api(tags = "在线用户")
@ApiSort(7)
@RestController
@RequestMapping("/online")
public class OnlineController {
    public static final String CURRENT_MODULE = "在线用户";

    @ApiOperationSupport(order = 1)
    @ApiOperation("获取在线用户列表")
    @GetMapping("/list")
    public ResultResponse<OnlineVO> listUser(OnlineQueryDTO onlineQueryDTO) {
        List<OnlineVO> onlineUserList = new ArrayList<>();
        // 获取所有已登录的会话id
        List<String> sessionIdList = StpUtil.searchSessionId("", 0, -1, false);
        for (String sessionId : sessionIdList) {
            // 根据会话id，查询对应的 SaSession 对象，此处一个 SaSession 对象即代表一个登录的账号
            SaSession session = StpUtil.getSessionBySessionId(sessionId);
            // 获得在线用户信息
            User user = (User) session.getDataMap().get("user");

            if (StrUtil.isBlank(onlineQueryDTO.getUsername()) ||
                    (StrUtil.isNotBlank(onlineQueryDTO.getUsername()) && user.getUsername().contains(onlineQueryDTO.getUsername()))) {
                    OnlineVO onlineVO = new OnlineVO();
                    BeanUtil.copyProperties(user, onlineVO);
                    onlineUserList.add(onlineVO);
            }
        }
        return ResultResponse.success().dataList(onlineUserList, Long.valueOf(onlineUserList.size()));
    }

    @MyLog(operation = "强制下线用户", module = CURRENT_MODULE)
    @ApiOperationSupport(order = 2)
    @ApiOperation("强制下线用户")
    @DeleteMapping("/{userIds}")
    public ResultResponse<Void> forceLogout(@PathVariable List<Long> userIds) {
        for (Long userId : userIds) {
            StpUtil.kickout(userId);
        }
        return ResultResponse.success().message("强制下线成功");
    }
}
